<template>
	<view class="container">
		<uni-section title="联系信息" type="line">
			<uni-list>
				<uni-list-item class="item" @click="bindMobile" title="手机号" :rightText="userInfo.mobile||'未绑定'" link>
				</uni-list-item>
				
			</uni-list>			
		</uni-section>
			<uni-section title="姓名" type="line">
				<uni-easyinput :errorMessage="isNickEmpty"  v-model="nick" />
			</uni-section>
		<unicloud-db v-slot:default="{data, loading, error}" ref="udb" collection="zgj-shop" :where="where"
			loadtime="manual">
			<view v-if="error">{{error.message}}</view>
			<view v-else-if="loading">正在加载...</view>
			<view v-else>
				<uni-section title="维修厂名称" type="line">
					<uni-easyinput :errorMessage="isNameEmpty"  v-model="name" />
				</uni-section>
				<uni-section title="维修厂地址" type="line">
					<uni-easyinput v-model="address" :errorMessage="isAddrEmpty" suffixIcon="location" @iconClick="chooseAddress" />
				</uni-section>
				<button type="primary" style="margin-top:20px" @click="save">保存</button>
			</view>
		</unicloud-db>
		<uni-id-pages-bind-mobile ref="bind-mobile-by-sms" @success="bindMobileSuccess"></uni-id-pages-bind-mobile>
	</view>
</template>

<script>
	const uniIdCo = uniCloud.importObject("uni-id-co")
	  import {
	    store,
	    mutations
	  } from '@/uni_modules/uni-id-pages/common/store.js'
	export default {
		data() {
			return {
				sms:false,
				id: '',
				nick:'',
				name: '',
				address: '',
				userId: '',
				cityCode: null,
				provCode:null,
				region:'',
				shopId:'',
				areaCode: null,
				where: ''
			}
		},
		onLoad(event) {
			console.log("regist", event, this.userInfo)
			this.userId = uniCloud.getCurrentUserInfo().uid
			this.shopId = this.userId.hashCode()
			if(this.userInfo.nickname){
				this.nick = this.userInfo.nickname
			}
			console.log("userid",this.userId,uniCloud.getCurrentUserInfo())
			this.where = "user_id=='" + this.userId + "'"
			this.$nextTick(() => {
				this.$refs.udb.loadData({
					clear: true
				}, (res) => {
					console.log(res)
					if (res.length > 0) {
						var rcrd = res[0]
						this.id = rcrd._id
						this.name = rcrd.name
						this.shopId = rcrd.shop_id
						this.address = rcrd.address
						this.cityCode = rcrd.city_code
						this.areaCode = rcrd.area_code
						this.provCode = rcrd.prov_code
						this.region = rcrd.region
					}
				})
			})
		},
		onShow(event){			
			console.log("Regist show",this.sms)
			if(this.sms){
				this.queryShop()
			}
		},
		computed:{
			userInfo() {
			  return store.userInfo
			},
			mobile(){
				return store.mobile
			},
			isNickEmpty(){
				return !this.nick || this.nick.trim() ===''
			},
			isNameEmpty(){
				return !this.name || this.name.trim() ===''
			},
			isAddrEmpty(){
				return !this.address || this.address.trim() === ''
			}
		},
		methods: {
			chooseAddress() {
				uni.chooseLocation({
					success: (res) => {
						console.log(res)
						this.address = res.address
						if(this.isNameEmpty){
							this.name = res.name
						}
					}
				})
			},
			imageUploaded(e) {
				console.log("upload succ", e)
				this.photos = e.tempFilePaths
			},
			bindMobile() {
				// #ifdef APP-PLUS
				uni.preLogin({
					provider: 'univerify',
					success: this.univerify(), //预登录成功
					fail: (res) => { // 预登录失败
						// 不显示一键登录选项（或置灰）
						console.log(res)
						this.bindMobileBySmsCode()
					}
				})
				// #endif
			
				// #ifdef MP-WEIXIN
				uni.showActionSheet({
					itemList: ["微信手机号绑定","验证码绑定"],
					success: (e) => {
						console.log(e)
						if(e.tapIndex===0){
							this.$refs['bind-mobile-by-sms'].open()
						}
						else{
							this.bindMobileBySmsCode()
						}
					}
				})
				
				// #endif
			
				// #ifdef H5
				//...去用验证码绑定
				this.bindMobileBySmsCode()
				// #endif
			},
			bindMobileBySmsCode() {
				this.sms = true
				console.log("bind by sms")
				uni.navigateTo({
					url: './bind-mobile/bind-mobile'
				})
			},
			bindMobileSuccess() {
				mutations.updateUserInfo(false,()=>{
					this.queryShop()
				})
				
			},
			queryShop(){
				this.sms = false
				if(this.userInfo.mobile){
					this.$http.get('/web/ai/shop', {
						phone: this.userInfo.mobile
					}, (resp) => {
						console.log("shop query",resp)
						if(resp  ){
							if(!this.name){
								this.name = resp.name
							}
							if(!this.address){
								this.address = resp.addr
							}
							if(!this.nick){
								this.nick = resp.contact
							}
						}
					})
				}
			},
			save() {
				if(this.isNameEmpty || this.isAddrEmpty || this.isNickEmpty) return
				if(!this.userInfo.mobile){
					uni.showModal({
						title:'错误提示',
						content:'请绑定手机号码',
						showCancel:false
					})
					return
				}
				mutations.updateUserInfo({nickname:this.nick})
			
				this.$http.post('/web/ai/address',{text:this.address},(resp)=>{
					console.log("vin:",resp)
					this.cityCode = resp.city_id
					this.provCode = resp.prov_id
					this.areaCode = resp.county_id || 0
					var region = ''
					if(resp.prov_name) region += resp.prov_name
					if(resp.city_name) region += resp.city_name
					if(resp.county_name) region += resp.county_name
					this.region = region
					this._saveDb()
				})
				
			},
			_saveDb(){
				var data = {
					name: this.name,
					address: this.address,
					city_code: this.cityCode,
					area_code: this.areaCode,
					user_id: this.userId,
					shop_id:this.shopId,
					prov_code:this.provCode,
					region:this.region
				}
				console.log("value",data)
				if(this.id===''){
					this.$refs.udb.add(data,{
						success:(res)=>{
							getApp().globalData.shop = data
							uni.navigateBack()
						}
					})
				}
				else{
					this.$refs.udb.update(this.id,data,{
						success:(res)=>{
							getApp().globalData.shop = data
							uni.navigateBack()
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.container {
		.uni-section {
			padding-bottom: 10px;

			.uni-easyinput {
				padding: 0 10px;
				box-sizing: border-box;
			}
		}

		.uni-file-picker {
			background-color: #fff;
			padding: 10px;
		}
	}
</style>